package controller;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import model.User;
import service.UserService;
import service.UserServiceImpl;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Random;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    private final UserService userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        generateCode(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String vcode = request.getParameter("vcode");  //用户输入的验证码

        String scode = (String) request.getSession().getAttribute("code");  // 生成的验证码
        System.out.println("用户输入验证码："+vcode);
        System.out.println("会话取出验证码："+scode);
        // 验证码错误
        if (!scode.equals(vcode)) {
            request.setAttribute("msg", "验证码错误！");
            request.getRequestDispatcher("/register.jsp").forward(request, response);
        }

        User userInDB = null;
        try {
            userInDB = userService.getUserByName(username);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        if (userInDB == null) {
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            boolean flag = userService.addUser(user);
            System.out.println(flag);
            if (flag) {
                request.setAttribute("msg", "注册成功！");
                request.getRequestDispatcher("/login.jsp").forward(request, response);
            } else {
                request.setAttribute("msg", "系统错误，请稍后重试！");
                request.getRequestDispatcher("/register.jsp").forward(request, response);
            }

        } else {
            request.setAttribute("msg", "用户名已存在！");
            request.getRequestDispatcher("/register.jsp").forward(request, response);
        }


    }


    private void generateCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Random random = new Random(System.currentTimeMillis());
        StringBuilder sb = new StringBuilder();

        char sc = 'a';
        for (int i = 0; i <= 4; i++) {
            int str = random.nextInt(62);
            if (str < 10) {
                sb.append(str);
            } else if (str < 36) {
                sc = (char) ((str - 10) + 'a');
                sb.append(sc);
            } else {
                sc = (char) ((str - 36) + 'A');
                sb.append(sc);
            }
        }

        BufferedImage image = new BufferedImage(60, 20, BufferedImage.TYPE_INT_RGB);
        Graphics graphics = image.getGraphics();
        graphics.setColor(Color.GRAY);
        graphics.fillRect(0, 0, image.getWidth(), image.getHeight());
        graphics.setColor(Color.blue);
        graphics.setFont(new Font("Time", Font.BOLD, 18));
        graphics.drawString(sb.toString(), 3, 17);
        graphics.dispose();
        ImageIO.write(image, "JPG", response.getOutputStream());
        System.out.println("生成的验证码：" + sb);

        // 将验证码保存到session
        request.getSession().setAttribute("code", sb.toString());
    }
}

